﻿using CCWin.SkinControl;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using xClient.Framework;
using xClient.Framework.BaseView;
using xClient.Framework.PlugCore;
using xClient.Framework.StaticResource;

namespace cMES1007
{
    public partial class frmESOPDetailAndImgEdit : Form
    {
        public DataGridViewRow _dgvChangeRow = null;
        public int iMaxSeq = 0;
        public string _strSKUName = "";
        private string _strCmd = "ADD";
        public frmESOPDetailAndImgEdit(string vCMD, object param = null)
        {
            InitializeComponent();

            this._strCmd = vCMD;
            if (param != null)
            {
                this._dgvChangeRow = (DataGridViewRow)param;
            }
        }

        private void InitialViewData()
        {
            if(this._dgvChangeRow != null)
            {
                this.txtESOPDetail_ID.Text = _dgvChangeRow.Cells[0].Value.ToString();
                this.txtSOPNameId.Text = _dgvChangeRow.Cells[1].Value.ToString();
                this.txtStepName.Text = _dgvChangeRow.Cells[2].Value.ToString();
                this.txtSequence.Text = _dgvChangeRow.Cells[4].Value.ToString();
                this.txtSOPDetailDescription.Text = this._dgvChangeRow.Cells[3].Value.ToString();
                this.txtIsValid.Text = _dgvChangeRow.Cells[5].Value.ToString();                
                this.dtpCreateTime.text = _dgvChangeRow.Cells[7].Value.ToString();
                this.txtCreateUser.Text = _dgvChangeRow.Cells[6].Value.ToString();
                this.dtpUpdateTime.text = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                this.txtUpdateUser.Text = StaticDictionary.Dictionary.UserID;
                dynamic _sopImages = _dgvChangeRow.Cells[10].Value;
                if (_sopImages != null)
                {
                    
                    if (_sopImages.GetType().ToString().ToUpper().Equals("SYSTEM.STRING"))
                    {
                        _sopImages = JsonConvert.DeserializeObject(_sopImages);
                    }
                    this.lstSOPIMages.Items.Clear();
                    foreach (var sopImage in _sopImages)
                    {
                        SkinListBoxItem _tmpItem = new SkinListBoxItem((string)sopImage.image_path);
                        this.lstSOPIMages.Items.Add(_tmpItem);
                    }
                }
            }
        }

        private void ClearFormInputData()
        {
            this.txtESOPDetail_ID.Text = "";
            this.txtESOPDetail_ID.Enabled = false;
            this.txtSOPNameId.Text = "";
            this.txtStepName.Text = "";
            this.txtSequence.Text = (iMaxSeq + 1).ToString();
            this.txtSOPDetailDescription.Text = "";
            this.txtIsValid.Visible = false;
            this.txtCreateUser.Text = StaticDictionary.Dictionary.UserID;
            this.txtUpdateUser.Text = "";
            this.dtpCreateTime.Text = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");            
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (CheckInputValidate())
            {
                this._dgvChangeRow.Cells[0].Value = this.txtESOPDetail_ID.Text;
                this._dgvChangeRow.Cells[1].Value = this.txtSOPNameId.Text.Trim();
                this._dgvChangeRow.Cells[2].Value = this.txtStepName.Text.Trim().ToUpper();
                this._dgvChangeRow.Cells[3].Value = this.txtSOPDetailDescription.Text.Trim();
                this._dgvChangeRow.Cells[4].Value = this.txtSequence.Text.Trim();                
                this._dgvChangeRow.Cells[5].Value = this.txtIsValid.Text;
                this._dgvChangeRow.Cells[6].Value = this.txtCreateUser.Text; 
                this._dgvChangeRow.Cells[7].Value = this.dtpCreateTime.text;
                this._dgvChangeRow.Cells[8].Value = this.txtUpdateUser.Text;
                this._dgvChangeRow.Cells[9].Value = this.dtpUpdateTime.text; 
                this._dgvChangeRow.Cells[10].Value = this.InitialSOPImages().ToArray();

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private bool CheckInputValidate()
        {
            bool _bResult = true;
            if (String.IsNullOrEmpty(this.txtSOPDetailDescription.Text.Trim()))
            {
                MessageBox.Show("SOP详细操作说明必须输入.");
                return false;
            }
            return _bResult;
        }
        
        private void lstSOPIMages_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //双击删除
            if (this.lstSOPIMages.Items.Count > 0)
            {
                DialogResult dialog = 
                MessageBox.Show("确定要删除此图片吗？", "系统提示", MessageBoxButtons.YesNo,
                     MessageBoxIcon.Warning,
                      MessageBoxDefaultButton.Button2);
                if(dialog == DialogResult.Yes)
                {
                    var result = Services.ServiceMethod.DeleteFileFromServer(this.lstSOPIMages.Items[this.lstSOPIMages.SelectedIndex].Text);
                    if (result.Status)
                    {
                        this.lstSOPIMages.Items.Remove(this.lstSOPIMages.Items[this.lstSOPIMages.SelectedIndex]);
                    }
                    else
                    {
                        MessageBox.Show("删除服务器文件失败..", "系统提示");
                    }
                }
            }
        }

        private void lstSOPIMages_MouseClick(object sender, MouseEventArgs e)
        {
            //双击显示图片
            if (this.lstSOPIMages.Items.Count > 0)
            {
                if (this.lstSOPIMages.SelectedIndex >-1)
                {
                    var _imgPath = this.lstSOPIMages.Items[this.lstSOPIMages.SelectedIndex].Text;
                    this.pcbSOPImage.Image = null;
                    this.pcbSOPImage.WaitOnLoad = false;
                    this.pcbSOPImage.SizeMode = PictureBoxSizeMode.Zoom;
                    this.pcbSOPImage.LoadAsync(Convert.ToString(_imgPath));
                }
            }
        }

        private void btnUploadImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog _managerFBD = new OpenFileDialog();
            _managerFBD.Multiselect = false;
            _managerFBD.Filter = "图片文件(*.jpg,*.png,*.bmp)|*.jpg|*.png|*.bmp";
            DialogResult dialogResult = _managerFBD.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                string _filePath = _managerFBD.FileName;
                this.pcbSOPImage.Image = null;
                this.pcbSOPImage.WaitOnLoad = false;
                this.pcbSOPImage.SizeMode = PictureBoxSizeMode.Zoom;
                var result = Services.ServiceMethod.UploadFileToServer(_filePath, this._strSKUName);
                if (result.Status)
                {
                    _filePath = result.Data.ToString();
                    this.pcbSOPImage.LoadAsync(_filePath);
                    SkinListBoxItem lstItem = new SkinListBoxItem(_filePath);
                    this.lstSOPIMages.Items.Add(lstItem);
                    MessageBox.Show("上传文件成功。", "系统提示");
                }
                else
                {
                    MessageBox.Show("上传图片失败，错误信息：" + result.Message, "系统提示");
                }

            }
        }

        private List<dynamic> InitialSOPImages()
        {
            List<dynamic> lstRes = new List<dynamic>();
            
            if (this.lstSOPIMages.Items.Count > 0)
            {
                for(var i=0;i<this.lstSOPIMages.Items.Count;i++)
                {
                    var res = new
                    {
                        sop_detail_id = this.txtESOPDetail_ID.Text.Trim(),
                        image_name = this.lstSOPIMages.Items[i].Text.Substring(this.lstSOPIMages.Items[i].Text.LastIndexOf("/")+1),
                        image_path = this.lstSOPIMages.Items[i].Text,
                        sequence = i + 1,
                        is_valid = "Y",
                        create_time = this.dtpCreateTime.Text,
                        create_user = this.txtCreateUser.Text,
                        update_time = this.dtpUpdateTime.Text,
                        update_uesr = this.txtUpdateUser.Text
                    };
                    lstRes.Add(res);
                }
            }

            return lstRes;
        }

        private void frmESOPDetailAndImgEdit_Load(object sender, EventArgs e)
        {
            if (_strCmd.ToUpper().Equals("ADD"))
            {
                this.ClearFormInputData();
                this.Text = "新增ESOP详细及操作示例图片信息";
                this.btnAdd.Text = "添加";
            }
            else if (_strCmd.ToUpper().Equals("EDIT"))
            {
                this.Text = "修改工站捡料信息";
                this.btnAdd.Text = "修改";

                this.InitialViewData();

                this.txtUpdateUser.Text = StaticDictionary.Dictionary.UserID;
                this.dtpUpdateTime.Text = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
            }
        }

        private void frmESOPDetailAndImgEdit_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Escape)
            {
                this.Close();
            }
        }
    }
}
